package com.my.lucky.service;

import com.my.lucky.model.Stock60Boll;
import com.my.lucky.repository.Stock60BollRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@Service
public class Stock60BollService {

    private static final Logger log = LoggerFactory.getLogger(Stock60BollService.class);

    @Autowired
    private Stock60BollRepository stock60BollRepository;

    /**
     * 保存或更新股票60分钟线Bollinger Bands数据
     * 当记录存在时，只更新非null字段
     */
    @Transactional
    public Stock60Boll saveOrUpdate(Stock60Boll stock60Boll) {
        if (stock60Boll == null) {
            throw new IllegalArgumentException("Stock60Boll cannot be null");
        }

        try {
            return stock60BollRepository.saveOrUpdate(stock60Boll);
        } catch (Exception e) {
            log.error("Failed to save or update Stock60Boll: {}", stock60Boll, e);
            throw new ServiceException("保存或更新股票60分钟线Bollinger Bands数据失败", e);
        }
    }

    /**
     * 批量保存或更新
     */
    @Transactional
    public List<Stock60Boll> saveOrUpdateAll(List<Stock60Boll> stock60Bolls) {
        if (stock60Bolls == null || stock60Bolls.isEmpty()) {
            return stock60Bolls;
        }

        try {
            return (List<Stock60Boll>) stock60BollRepository.saveOrUpdateAll(stock60Bolls);
        } catch (Exception e) {
            log.error("Failed to batch save or update Stock60Boll", e);
            throw new ServiceException("批量保存或更新股票60分钟线Bollinger Bands数据失败", e);
        }
    }

    /**
     * 根据股票代码和交易日期查询
     */
    public Optional<Stock60Boll> findByCodeAndTradeDate(String code, LocalDate tradeDate) {
        if (code == null || code.trim().isEmpty() || tradeDate == null) {
            return Optional.empty();
        }

        return stock60BollRepository.findByCodeAndTradeDate(code, tradeDate);
    }

    /**
     * 自定义业务异常
     */
    public static class ServiceException extends RuntimeException {
        public ServiceException(String message, Throwable cause) {
            super(message, cause);
        }
    }
}